//数据埋点
import util from './util2';
import Config from './config2.js'
const sensors = require('./sensorsdata.min.js');
const sensorsdata_conf = require("./sensorsdata_conf");
const event = require('./event.js')
util.clearStorageKey(Config.retainKey)
wx.setStorageSync("visit_id", util.generateUUID());


sensors.setPara(sensorsdata_conf);
sensors.initWithOpenid();
const originalApp = App,
    originalPage = Page,
    orginalComponent = Component;

const _extendsApp = function (name, conf, method) {
    const _o_method = conf[method];
    conf[method] = function (ops) {
        if (typeof _o_method === 'function') {
            _o_method.call(this, ops);
        }
        //此处改成消息发布
        if (typeof event != "undefined") {
            event.emit(name + method, ops);
        }

    }
}
const _extendsPage = function (conf, method) {
    const _o_method = conf[method];
    conf[method] = function (ops) {
        if ("onShow" === method) {
            let pageVisitStartTime = wx.getStorageSync("pageVisitStartTime");
            let page_visit_time = null;
            if (!pageVisitStartTime) {//重新打开或者首次打开页面，开始计时{
                pageVisitStartTime = new Date().getTime();
            } else {//有开始时间，证明是切换页面操作，计算上一个页面的页面停留时间
                //console.log('怎么会执行呢？',pageVisitStartTime)
                let pageVisitEndTime = new Date().getTime();
                page_visit_time = (pageVisitEndTime - pageVisitStartTime) / 1000.0;//得出页面停留时间
                pageVisitStartTime = new Date().getTime();//开始时间重新开始算
            }
            wx.setStorageSync("pageVisitStartTime", pageVisitStartTime);
            sensors.para.autoTrack.pageShow = {
                query: {},
                ..._setParam(),
                page_visit_time
            };
        } else if ("onShareAppMessage" === method) {
            sensors.para.autoTrack.pageShare = {
                query: {},
                ..._setParam()
            }
        }
        if (typeof _o_method === 'function') {
            _o_method.call(this, ops);
        }
    }
}
const _setParam = function () {
    return {
        account_id: wx.getStorageSync("userId"),
        visit_id: wx.getStorageSync("visit_id")
    }
}

App = function (conf) {
    const methods = ['onLaunch', 'onShow', 'onHide', 'onError'];
    methods.map(function (method) {
        _extendsApp('app', conf, method);
    });
    conf.globalData.sensors = sensors;
    //启动小程序
    event.on('apponLaunch', this, function (options) {
        sensors.para.autoTrack.appLaunch = {
            appId: options.referrerInfo.appId,
            query: options.query,
            extraData: options.referrerInfo.extraData,
            ..._setParam()

        };
    })
    //显示小程序
    event.on('apponShow', this, function (options) {
        /*wx.removeStorage({
            key: 'pageVisitStartTime'
        })*/
        sensors.para.autoTrack.appShow = {
            query: options,
            ..._setParam()
        }
    })
    //小程序进入后台
    event.on('apponHide', this, function () {
        let pageVisitStartTime = wx.getStorageSync("pageVisitStartTime");
        let page_visit_time = 0;
        if (!pageVisitStartTime) {//正常应该能够获取到开始时间的，因为有onHide肯定之前就有MpViewSreen（即有打开页面，有打开页面就有开始时间）
            page_visit_time = null//没有开始时间，异常，不统计这次的页面访问时间
        } else {//有开始时间，证明是切换页面操作
            let pageVisitEndTime = new Date().getTime();
            page_visit_time = (pageVisitEndTime - pageVisitStartTime) / 1000.0;//得出页面停留时间
            //清空开始时间
            try {
                wx.removeStorageSync('pageVisitStartTime')
            } catch (e) {
            }
        }
        sensors.para.autoTrack.appHide = {
            query: {},
            ..._setParam(),
            page_visit_time: page_visit_time
        }
    })
    return originalApp(conf);


}
Page = function (conf) {
    const methods = ['onLoad', 'onShow', 'onReady', 'onHide', 'onUnload'];
    const app = getApp()
    if(conf.data) conf.data.app=app;
    methods.map(function (method) {
        _extendsPage(conf, method);
    });
    return originalPage(conf);
}
